/*
 * Copyright 2012 The Eventio Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.eventio;

/**
 * 
 * This is a holder that stores results of calls that may throw exceptions. It
 * makes it possible to re-throw the execption when the result value is
 * retrieved.
 * 
 * @author steph
 * 
 * @param <T>
 */
public class Result<T> {

	private final T result;
	private final RuntimeException exception;

	public Result(T result) {
		this.result = result;
		this.exception = null;
	}

	public Result(Throwable t) {
		this.exception = new RuntimeException(t);
		result = null;
	}

	/**
	 * returns the result, unless some exception arose, in which case the
	 * exception is thrown, wrapped in a {@link RuntimeException}
	 * 
	 * @return the result, if it could be retrieved
	 * @throws RuntimeException
	 *             if an exception was caught while trying to getting this
	 *             result
	 */
	public T get() throws RuntimeException {
		if (exception != null) {
			throw exception;
		}
		return result;
	}

	@Override
	public String toString() {
		if (exception != null) {
			return exception.getCause().toString();
		}
		if (result != null) {
			return result.toString();
		}
		return "null";
	}

	public static <T> Result<T> wrap(T result) {
		return new Result<T>(result);
	}

}
